<template>
  <div class="authorize-card">
    <ContainerContent :loading="loading" :pagination="false">
      <div class="authorize-card-content">
        <div class="authorize-card-item">
          <div class="authorize-card-key">授权状态</div>
          <div class="authorize-card-value">
            <div
              class="authorize-status"
              :class="{
                'authorize-status--success': LicenseDetails.status == 1,
                'authorize-status--error': [2, 3, 4].includes(
                  LicenseDetails.status
                )
              }">
              <span>{{
                getOptionLabel(LicenseDetails.status, authStatusOptions)
              }}</span>
            </div>
            <span
              v-if="
                [2, 3].includes(LicenseDetails.status) && LicenseDetails.reason
              ">
              ( 异常代码：{{ LicenseDetails.reason || '-' }})</span
            >
            <i-icons-refresh
              class="text-[#D9D9D9] cursor-pointer hover:text-1"
              @click="refreshLicense" />
          </div>
        </div>
        <div class="authorize-card-item">
          <div class="authorize-card-key">到期时间</div>
          <div class="authorize-card-value">
            <span
              :class="{
                'text-[#FF7D00]':
                  calculateRemainingDays(LicenseDetails.expired_at) < 14 &&
                  calculateRemainingDays(LicenseDetails?.expired_at) > -1 &&
                  LicenseDetails.expired_at,
                'text-[#ED3C3C]':
                  calculateRemainingDays(LicenseDetails.expired_at) < 0 &&
                  LicenseDetails.expired_at
              }">
              {{ ExpirationAt(LicenseDetails.expired_at) || '-' }}</span
            >
            <span
              v-if="calculateRemainingDays(LicenseDetails.expired_at) >= 0"
              class="text-4 text-xs"
              >(剩余&nbsp;{{
                calculateRemainingDays(LicenseDetails.expired_at)
              }}&nbsp;天)</span
            >
          </div>
        </div>
        <div class="authorize-card-item">
          <div class="authorize-card-key">授权码</div>
          <div class="authorize-card-value">
            {{ LicenseDetails.key || '-' }}
          </div>
        </div>
        <div class="authorize-card-btns">
          <a-button
            v-if="LicenseDetails.status === 0"
            type="primary"
            @click="ActiveOpen"
            ><i-icons-activation /> 激活
          </a-button>
          <a-button
            v-if="LicenseDetails.status !== 0"
            :disabled="[2, 3].includes(LicenseDetails.status)"
            type="primary"
            @click="Unbind"
            ><i-icons-unbind /> 解绑
          </a-button>
          <a-button
            v-if="LicenseDetails.status !== 0"
            :disabled="[2, 3].includes(LicenseDetails.status)"
            type="primary"
            @click="ChangeOpen"
            ><i-icons-change-bind /> 换绑
          </a-button>
        </div>
      </div>
    </ContainerContent>
    <!-- <ActivationBind
      v-model:visible="ActiveVisible"
      :record="LicenseDetails"
      @reload="getLicense"></ActivationBind> -->
    <ActivationBind
      v-model:visible="ActiveVisible"
      @reload="getLicense"></ActivationBind>
    <ChangeBind
      v-model:visible="ChangeVisible"
      @reload="getLicense"></ChangeBind>
  </div>
</template>
<script lang="ts" setup>
import ContainerContent from '@/components/ContentContainer.vue'
import {
  getApiLicenseDetailApi,
  postApiLicenseUnbindApi,
  postApiLicenseRefreshApi
} from '@/apis/modules/resolve/license'
import ChangeBind from './components/ChangeBind.vue'
import ActivationBind from './components/ActivationBind.vue'
import dayjs from 'dayjs'
import { useAppStore } from '@/stores/app'
import { getOptionLabel } from '@/utils/format'
import { authStatusOptions } from '@/constants/auth'
const appStore = useAppStore()
const LicenseDetails = ref({
  expired_at: 0,
  key: '',
  reason: '',
  status: 0
})
const loading = ref<boolean>(false)
const { visible: ActiveVisible, open: ActiveOpen } = usePopup()
const { visible: ChangeVisible, open: ChangeOpen } = usePopup()
// 获取授权信息
const getLicense = () => {
  loading.value = true
  getApiLicenseDetailApi({})
    .then((res) => {
      LicenseDetails.value = res
      appStore.setAuthInfo(res)
    })
    .finally(() => {
      loading.value = false
    })
}

const refreshLicense = () => {
  loading.value = true
  postApiLicenseRefreshApi({})
    .then((res) => {
      LicenseDetails.value = res
      appStore.setAuthInfo(res)
    })
    .finally(() => {
      loading.value = false
    })
}
const ExpirationAt = (data: number | 0) => {
  if (data) {
    const template = 'YYYY-MM-DD HH:mm:ss'
    return dayjs(data * 1000).format(template)
  } else {
    return '-'
  }
}

const calculateRemainingDays = (timestamp: number | 0) => {
  // 获取当前时间的时间戳（单位：秒）
  const now = Math.floor(Date.now() / 1000)
  const remainingTime = timestamp - now
  // 计算剩余天数
  const days = Math.floor(remainingTime / (60 * 60 * 24))
  return days
}

const Unbind = () => {
  CloudModal.error(
    {
      content: `确认解绑授权？`,
      okText: '确定'
    },
    () =>
      postApiLicenseUnbindApi({}).then(() => {
        getLicense()
        ToastUtils.success('解绑成功')
      })
  )
}

onMounted(getLicense)
</script>
<style lang="less" scoped>
.authorize-card {
  .authorize-card-content {
    display: flex;
    flex-direction: column;
    gap: 16px;

    min-width: 290px;
    .authorize-card-item {
      display: flex;
      align-items: center;
      gap: 8px;
      align-self: stretch;
      .authorize-card-key {
        color: var(----1color-text-4, #8f959e);
        font-size: 14px;
        line-height: 22px; /* 157.143% */
        width: 72px;
      }
      .authorize-card-value {
        display: flex;
        align-items: center;
        gap: 8px;
        align-self: stretch;
      }
    }
    .authorize-card-more {
      display: flex;
      height: 20px;
      padding: 0px 4px;
      display: flex;
      align-items: flex-end;
      flex-direction: column;
      align-items: flex-end;
      cursor: pointer;
      color: #11429d;
      &:hover {
        color: #7fa7d8;
      }
    }
    .authorize-card-btns {
      display: flex;
      align-items: flex-start;
      gap: 16px;
    }
  }
  .authorize-status {
    display: flex;
    height: 20px;
    padding: 1px 6px;
    justify-content: center;
    align-items: center;
    gap: 10px;
    border-radius: 4px;
    background: var(---color-text-6, #adafb2);
    color: var(---color-white, #fff);
    font-size: 12px;
    font-weight: 400;
    line-height: 20px; /* 166.667% */
    &.authorize-status--success {
      background: var(---success-6, #14af9c);
    }
    &.authorize-status--error {
      background: var(---success-6, #ed3c3c);
    }
  }
}
</style>
